<template>
  <div ref="containerRef" class="gantt-container">
    <g-gantt-chart chart-start="2025-01-01 00:00:00" chart-end="2025-12-19 23:59:59" precision="day"
      date-format="YYYY-MM-DD HH:mm:ss" bar-start="beginDate" bar-end="endDate" color-scheme="dark" grid
      class="full-width-gantt" row-height="40">
      <template #upper-timeunit="{ value }">
        <h1>
          {{
            moment(value).format('YYYY-MM')
          }}
        </h1>
      </template>
      <template #timeunit="{ value }">
        <el-text style="text-align: left;width: 100%;">{{ moment(value).format('MM.DD') }}</el-text>
      </template>
      <template #label-column-row="{ label }">
        <el-tooltip class="box-item" effect="dark" :content="`${label.roomName}，可容纳：${label.capacity}人`"
          placement="right">
          <el-text style="width: 270px;" :truncated="true">{{
            label
          }}，{{ label.capacity }}人
          </el-text>
        </el-tooltip>
      </template>

      <g-gantt-row v-for="(item, index) in context" :key="index" :bars="item" label="??" highlight-on-hover />
    </g-gantt-chart>
  </div>
</template>
<script setup lang="ts">
import moment from "moment";
import { ref, onMounted, onUnmounted, type Ref } from "vue";
// import { GGanttChart, GGanttRow } from "@infectoone/vue-ganttastic";

const scrollLeft = ref(0);
const containerRef: Ref<HTMLElement | null> = ref(null);

// 修复：重复的id改为唯一值（最后一个元素id从6改为7）
const context = ref([
  [
    {
      beginDate: "2025-02-10 00:00:00",
      endDate: "2025-02-17 00:00:00",
      label_column_title: "123",
      ganttBarConfig: {
        id: "0",
        hasHandles: true,
        label: "需求收集和分析  负责人：小张",
        style: { background: "#e96560" }
      }
    }
  ],
  [
    {

      beginDate: "2025-02-10 09:00:00",
      endDate: "2025-03-17 18:00:00",
      ganttBarConfig: {
        id: "1",
        hasHandles: true,
        label: "系统设计  负责人：小强",
        style: { background: "#5ccfa3" }
      }
    }
  ],

  // [
  //   {
  //     week: "星期三",
  //     beginDate: "07:00",
  //     endDate: "20:00",
  //     ganttBarConfig: {
  //       id: "2",
  //       hasHandles: true,
  //       label: "编码实现  负责人：老李",
  //       style: { background: "#77d6fa" }
  //     }
  //   }
  // ],
  // [
  //   {
  //     week: "星期四",
  //     beginDate: "06:00",
  //     endDate: "21:00",
  //     ganttBarConfig: {
  //       id: "3",
  //       hasHandles: true,
  //       label: "编码实现  负责人：小明",
  //       style: { color: "#fff", background: "#1b2a47" }
  //     }
  //   }
  // ],
  // [
  //   {
  //     week: "星期五",
  //     beginDate: "05:00",
  //     endDate: "19:00",
  //     ganttBarConfig: {
  //       id: "4",
  //       hasHandles: true,
  //       label: "内部测试  负责人：小雪",
  //       style: { background: "#5ccfa3" }
  //     }
  //   }
  // ],
  // [
  //   {
  //     week: "星期六",
  //     beginDate: "10:00",
  //     endDate: "22:00",
  //     ganttBarConfig: {
  //       id: "5",
  //       hasHandles: true,
  //       label: "系统优化和文档整理  负责人：小欣",
  //       style: { background: "#f8bc45" }
  //     }
  //   }
  // ],
  // [
  //   {
  //     week: "星期天",
  //     beginDate: "04:00",
  //     endDate: "23:59",
  //     ganttBarConfig: {
  //       id: "6",
  //       immobile: false,
  //       hasHandles: false,
  //       label: "部署和上线  负责人：老王",
  //       style: { background: "#f3953d" }
  //     }
  //   }
  // ],
  // [
  //   {
  //     week: "星期天",
  //     beginDate: "04:00",
  //     endDate: "23:59",
  //     ganttBarConfig: {
  //       id: "7", // 修复：id改为唯一值7
  //       immobile: false,
  //       hasHandles: false,
  //       label: "部署和上线  负责人：老王",
  //       style: { background: "#f3953d" }
  //     }
  //   }
  // ]
]);

// 移除冗余的滚动处理逻辑（改用CSS sticky定位）
onMounted(() => {
  if (containerRef.value) {
    console.log("容器已挂载");
    // 计算百分比
    const percentage = getDayOfYearPercentage();
    console.log(`当前日期在今年的百分比: ${percentage}%`);

    // 定位滚动条（假设容器宽度为scrollWidth）
    const container = containerRef.value;
    if (container.scrollWidth) {
      // 滚动到对应百分比位置
      container.scrollLeft = (container.scrollWidth * percentage) / 100;
    }
  }
});

onUnmounted(() => {
  console.log("组件已卸载");
});

// 计算当天日期在一年中的百分比（按天算）
function getDayOfYearPercentage() {
  const today = new Date();
  const year = today.getFullYear();

  // 判断是否为闰年（闰年2月有29天，全年366天）
  const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  const totalDays = isLeapYear ? 366 : 365;

  // 计算当年1月1日
  const startOfYear = new Date(year, 0, 1);
  // 计算从年初到今天的毫秒差
  const timeDiff = today.getTime() - startOfYear.getTime();
  // 转换为天数（+1是因为包含当天）
  const dayOfYear = Math.floor(timeDiff / (1000 * 60 * 60 * 24)) + 1;

  // 计算百分比（保留两位小数）
  const percentage = (dayOfYear / totalDays) * 100;
  return parseFloat(percentage.toFixed(2));
}

// 修复：本周日期计算逻辑（适配中国周一为一周开始）
function getWeekRange() {
  const today = new Date();
  const dayOfWeek = today.getDay();

  const startDate = new Date(today);
  startDate.setDate(today.getDate() - dayOfWeek + 1);

  const endDate = new Date(startDate);
  endDate.setDate(startDate.getDate() + 6);

  const formatDate = (date: any) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  };

  const currentWeekStart = formatDate(startDate);
  const currentWeekEnd = formatDate(endDate);

  return {
    currentWeekStart,
    currentWeekEnd
  };
}

const weekRangeInChina = getWeekRange();
</script>



<style>
/* 修复：使用sticky定位固定标签，替代JS计算 */
.g-gantt-row-label,
.g-gantt-row-label-container {
  position: sticky !important;
  left: 0 !important;
  background: white !important;
  /* 避免滚动时内容重叠 */
  z-index: 10 !important;
  transition: none !important;
}

.gantt-container {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 10px;
}

.full-width-gantt {
  min-width: 15000px;
  width: 200%;
}

.g-gantt-row-label {
  width: 100px !important;
  min-width: 100px !important;
  max-width: 100px !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}
</style>